package com.briup.pts.service.impl;

import com.briup.pts.config.exception.ServiceException;
import com.briup.pts.config.response.ResultCode;
import com.briup.pts.domain.bean.FenceHouse;
import com.briup.pts.domain.vo.FenceHouseVO;
import com.briup.pts.mapper.FenceHouseMapper;
import com.briup.pts.service.FenceHouseService;
import com.briup.pts.utils.UuidUtil;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.List;
import java.util.Objects;

@Service
@RequiredArgsConstructor
public class FenceHouseServiceImpl implements FenceHouseService {

    private final FenceHouseMapper fenceHouseMapper;

    @Override
    public PageInfo<FenceHouse> pageQueryByConditional(Integer pageNum, Integer pageSize, String fhName) {
        // 开启分页
        try (Page<FenceHouse> ignored = PageHelper.startPage(pageNum, pageSize)) {
            // 根据条件查询数据
            List<FenceHouse> fenceHouses = fenceHouseMapper.queryByConditional(fhName);
            Page<FenceHouse> records = (Page<FenceHouse>) fenceHouses;
            // 转换并返回分页数据
            return new PageInfo<>(records);
        }
    }

    @Override
    public FenceHouseVO queryById(String fhId) {
        return fenceHouseMapper.queryById(fhId);
    }

    @Override
    public void saveOrUpdate(FenceHouse fenceHouse) {
        String fhId = fenceHouse.getFhId();

        // 为了保证栏舍的名字唯一，对其进行校验
        FenceHouse house = fenceHouseMapper.queryByName(fenceHouse.getFhName());
        // 如果根据名称查询栏舍信息，发现栏舍对象不为null，并且不是当前需要修改的栏舍，那么直接说明该栏舍已经存在
        if (house != null && !Objects.equals(house.getFhId(), fhId)) {
            throw new ServiceException(ResultCode.FENCE_HOUSE_IS_EXISTS);
        }

        // 根据id区分是新增还是修改
        if (StringUtils.hasText(fhId)){
            // 修改
            fenceHouseMapper.updateFenceHouse(fenceHouse);
        }else {
            // 新增栏舍，需要自己生成栏舍的id
            fenceHouse.setFhId(UuidUtil.randomUUID());
            fenceHouseMapper.addFenceHouse(fenceHouse);
        }
    }

    @Override
    public void batchDelete(List<String> ids) {
        fenceHouseMapper.batchDelete(ids);
    }
}
